package com.fate.system.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fate.framework.exception.KKException;
import com.fate.framework.utils.CommonUtil;
import com.fate.framework.utils.SmUtil;
import com.fate.framework.utils.SystemUtil;
import com.fate.system.constant.RoleConst;
import com.fate.system.constant.UserConst;
import com.fate.system.dto.user.UserPageDTO;
import com.fate.system.entity.User;
import com.fate.system.mapper.UserMapper;
import com.fate.system.service.IRoleService;
import com.fate.system.service.IUserService;
import jakarta.annotation.Resource;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 47349
 * @description 针对表【sys_user(用户表)】的数据库操作Service实现
 * @createDate 2024-08-09 02:11:25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

  @Resource private IRoleService roleService;

  public Page<User> getPageList(UserPageDTO pageDTO) {
    String nickname = pageDTO.getNickname();
    String phone = pageDTO.getPhone();
    String sex = pageDTO.getSex();
    List<String> userIds = pageDTO.getUserIds();

    Page<User> page = SystemUtil.buildPageFromDTO(pageDTO, User.class);
    return this.lambdaQuery()
        .in(CommonUtil.notNullOrEmpty(userIds), User::getId, userIds)
        .like(CommonUtil.notNullOrEmpty(nickname), User::getNickname, nickname)
        .like(CommonUtil.notNullOrEmpty(phone), User::getPhone, phone)
        .eq(CommonUtil.notNullOrEmpty(sex), User::getSex, sex)
        .orderByDesc(User::getGmtCreate)
        .page(page);
  }

  @Override
  public SaTokenInfo login(User user) {
    List<String> roleIds = user.getRoleIds();
    // 获取角色标识列表
    List<String> roleSigns = roleService.getRoleSignsByIds(roleIds);

    // 登录获取token信息
    StpUtil.login(user.getId());
    SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

    // 注入sa-token
    StpUtil.getSession().set("roleList", roleSigns);
    //    StpUtil.getSession().set("tenantId", user.getTenantId());
    //    StpUtil.getSession().set("loginName", user.getUsername());

    return tokenInfo;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void register(String phone, String password) {
    Long count = this.lambdaQuery().eq(User::getPhone, phone).count();
    if (count > 0) {
      throw new KKException("该手机号已被注册");
    }
    User user = new User();
    user.setPhone(phone);
    user.setPassword(SmUtil.sm3(password));

    String roleId = roleService.getRoleIdBySign(RoleConst.DEFAULT_ROLE);

    user.setRoleIds(List.of(roleId));
    user.setNickname(UserConst.DEFAULT_USERNAME);
    this.save(user);
  }

  @Override
  public void removeUser(String id) {
    User user = this.getById(id);
    if (CommonUtil.isNullOrEmpty(user)) {
      throw new KKException("用户不存在");
    }
    List<String> roleIds = user.getRoleIds();
    List<String> roleSigns = roleService.getRoleSignsByIds(roleIds);

    if (roleSigns.contains(RoleConst.DEFAULT_ROLE)) {
      throw new KKException("该角色用户不能删除，如有需求，请联系管理员");
    }
    this.removeById(id);
  }
}
